package org.suwenqian.airoleplayingchatbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.stereotype.Service;

import org.suwenqian.airoleplayingchatbackend.dao.dto.req.ChatReqDTO;
import org.suwenqian.airoleplayingchatbackend.dao.entity.RoleDO;
import org.suwenqian.airoleplayingchatbackend.dao.mapper.RoleMapper;
import org.suwenqian.airoleplayingchatbackend.service.ChatService;
import reactor.core.publisher.Flux;


@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatClient.Builder chatClientBuilder;
    private final ChatMemory redisChatMemory;
    private final RoleMapper roleMapper;

    @Override
    public Flux<String> streamMessage(ChatReqDTO requestParm) {
        // 1. 根据传入的角色ID获取角色设定与背景构建消息体
        LambdaQueryWrapper<RoleDO> eq = Wrappers.lambdaQuery(RoleDO.class)
                .eq(RoleDO::getId, requestParm.getRoleId());
        RoleDO roleDO = roleMapper.selectOne(eq);
        ChatClient dynamicChatClient = chatClientBuilder
                .defaultSystem(roleDO.getPromptTemplate()) // 角色设定
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(redisChatMemory).build(),
                        new SimpleLoggerAdvisor()
                )
                .build();

        // 2. 返回请求响应
        return dynamicChatClient.prompt()
                .user(requestParm.getContent())
                .advisors(a -> a.param("chatMemoryConversationIdKey", requestParm.getConversationId()))
                .stream()
                .content()
                .onErrorResume(e -> Flux.just("【服务暂时不稳定，请稍后再试】"));

    }
}
